package com.nw.serviceImpl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
//import com.nw.config.AlipayConfig;
import com.nw.dao.CargoDao;
import com.nw.dao.CommentPermissionDao;
import com.nw.dao.OrderItemDao;
import com.nw.entity.Cargo;
import com.nw.entity.CommentPermission;
import com.nw.entity.Order;
import com.nw.entity.OrderItem;
import com.nw.service.CommentPermissionService;
import com.nw.service.OrderItemService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class OrderItemServiceImpl implements OrderItemService {
    @Resource
    OrderItemDao orderItemDao;
    @Resource
    CargoDao cargoDao;
    @Resource
    HttpServletResponse response;
    @Resource
    CommentPermissionDao commentPermissionDao;



    @Override
    public HashMap<String, Object> insertOrderItems(OrderItem orderItems) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            String parentId = UUID.randomUUID().toString();
            System.out.println(orderItems);
            orderItems.setParentId(parentId);
            System.out.println("存入数据库的数据:"+orderItems);
            orderItemDao.insertOrderItem(orderItems);

            CommentPermission commentPermission = new CommentPermission();
            commentPermission.setCommentPermissionId(UUID.randomUUID().toString());
            commentPermission.setCommentUserId(orderItems.getOrderItemUsername());
            commentPermission.setCommentCargoId(orderItems.getOrderItemId());
            commentPermission.setCommentTimeRemain("3");
            commentPermissionDao.addCommentPermission(commentPermission);

            map.put("code","0");
            map.put("msg","提交成功");
            map.put("parentId",parentId);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg", "提交失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> insertOrder(OrderItem orderItems) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            Order order = new Order();
            String orderId = UUID.randomUUID().toString();
            order.setOrderId(orderId);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String nowTime = simpleDateFormat.format(date);
            try {
                Date nowTimeDate = simpleDateFormat.parse(nowTime);
                order.setOrderTime(nowTimeDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String parentId = orderItems.getParentId();
            Double totalPrice = orderItems.getOrderItemTotalPrice();

            //获取购物车内商品的数量
            int orderItemNumber = orderItems.getOrderItemNumber();
            int cargoSaled = cargoDao.queryCargoById(orderItems.getOrderItemId()).getCargoSaled();
            int cargoRemain = cargoDao.queryCargoById(orderItems.getOrderItemId()).getCargoRemain();
            System.out.println("订单系统本次购买的数量为:" + orderItemNumber);
            System.out.println("订单系统已售出的数量为:" + cargoSaled);
            System.out.println("订单系统已购买的数量为:" + cargoRemain);

            int newCargoSaled = orderItemNumber + cargoSaled;
            int newCargoRemain = cargoRemain - orderItemNumber;
            Cargo cargo = new Cargo();
            cargo.setCargoSaled(newCargoSaled);
            cargo.setCargoRemain(newCargoRemain);
            cargo.setCargoId(orderItems.getOrderItemId());
            cargoDao.updateNumber(cargo);
            order.setOrderTotalPrice(totalPrice);
            //未支付0
            order.setOrderStatus("0");
            order.setParentId(parentId);
            System.out.println("插入数据库的订单数据:" + order);
            orderItemDao.insertOrder(order);

            map.put("code","0");
            map.put("msg","添加成功");
            map.put("parentId",parentId);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","添加失败");

        }


        /*//获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
        aliPayRequest.setReturnUrl(AlipayConfig.return_url);
        aliPayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String order_number = new String(orderId);
        String total_amount = new String(totalPrice.toString());
        String subject = new String("支付宝沙箱支付");
        aliPayRequest.setBizContent("{\"out_trade_no\":\"" + order_number + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(aliPayRequest).getBody();
            System.out.println(result);response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(result);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException | IOException e) {
            e.printStackTrace();
        }*/
        return map;
    }


    @Override
    public HashMap<String, Object> queryOrderByReceiver(String receiver) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            List<Order> orders = orderItemDao.queryOrderByReceiver(receiver);
            if (orders != null) {
                map.put("code","0");
                map.put("msg","查询成功");
                map.put("data",orders);
            }else {
                map.put("code","1");
                map.put("msg","查询空值，好好寻思下");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","查询失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> updateOrderStatus(Order order) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            System.out.println("修改的订单参数为:"+order);
            orderItemDao.updateOrderStatus(order);
            map.put("code","0");
            map.put("msg","修改订单状态成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","修改订单状态失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> queryAllOrder() {
        HashMap<String, Object> map = new HashMap<>();
        try {
            List<Order> orders = orderItemDao.queryAllOrder();
            map.put("code","0");
            map.put("msg","查询所有订单成功");
            map.put("data",orders);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code","1");
            map.put("msg","查询所有订单失败");
        }
        return map;
    }


}
